package com.mywork.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;
import com.spring.MyApplicationContext;
import sun.font.CreatedFontTracker;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println("初始化前");
        if (beanName.equals("user1")){
            ((UserService)bean).setBeanName("userService");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("初始化后");
//        在初始化后我们可以进行代理  来实现AOP
        if (beanName.equals("userService")){
//            JDK原生代理 增强接口中的test方法
            Object proxyInstance =Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(), UserService.class.getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("代理之前");
                    return method.invoke(bean, args);

                }
            });
            return proxyInstance;
        }

        return bean;
    }
}
